﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Nwsfeed
{
    [Serializable()]
    public class Application : ISerializable
    {
        private SHA256CryptoServiceProvider cr;
        private Dictionary<string, UserProfile> profiles;
        private UserProfile activeProfile;

        public Application()
        {
        }

        public Application(SerializationInfo info, StreamingContext context)
        {
            this.profiles = (Dictionary<string, UserProfile>)info.GetValue(
                "Profiles", typeof(Dictionary<string, UserProfile>));
        }

        public void Initialize()
        {
            cr = new SHA256CryptoServiceProvider();
            profiles = new Dictionary<string, UserProfile>();

            Stream stream;
            try
            {
                stream = File.Open("appconfig.dat", FileMode.Open);

                if (stream.Length != 0)
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    Application app = (Application)bf.Deserialize(stream);
                    this.profiles = app.profiles;
                }
                stream.Close();
            }
            catch (System.IO.FileNotFoundException)
            {
                return;
            }
        }

        public bool CreateUserProfile(string username, string password)
        {
            if (profiles.ContainsKey(username))
                return false;

            byte[] data = Encoding.ASCII.GetBytes(password);
            data = cr.ComputeHash(data);
            string passSHA256Hash = Encoding.ASCII.GetString(data);

            UserProfile p = new UserProfile(username, passSHA256Hash);
            profiles.Add(p.Username, p);

            // save
            Stream stream = File.Open("appconfig.dat", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, this);
            stream.Close();

            return true;
        }

        public bool LogIn(string username, string password)
        {
            if (profiles.ContainsKey(username))
            {
                byte[] data = Encoding.ASCII.GetBytes(password);
                data = cr.ComputeHash(data);
                if (Encoding.ASCII.GetString(data) == profiles[username].PassSHA256Hash)
                {
                    activeProfile = profiles[username];
                }
                    return true;
            }
            return false;
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Profiles", this.profiles);
        }
    }
}
